package com.bq.gametrade.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.ResponseBean;
import com.bq.gametrade.bean.UserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.ui.dialog.CuttingPictureDialog;
import com.bq.gametrade.utils.BitmapUtils;
import com.bq.gametrade.utils.FileUpload;
import com.bq.gametrade.utils.NetworkUtils;
import com.bq.gametrade.view.CircleImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class PersonalDataActivity extends BaseActivity implements View.OnClickListener, CuttingPictureDialog.HeadIconPathListener {

    private ImageView back;
    private TextView tvTitle, tvUpdatePhoneNo;
    private EditText etNickName, etPhoneNumber, edBqAccount;
    private Button btnConfirm;
    private CircleImageView userHeadImage;
    private String userheadImage = "";
    private FileUpload fileUpload = new FileUpload();
    private UserInfoDetails userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personaldata);
        setImageCacheFile();
        if(application.isLogin()){
            userInfo = application.getUserInfo();
        }else {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
        Glide.get(PersonalDataActivity.this).clearMemory();
        new Thread(clearCache).start();
        upload();
        initView();
        if (application.isLogin()) {
            setData();
        }
    }


    private void initView() {
        back = serchViewById(R.id.image_back);
        back.setOnClickListener(this);
        tvTitle = serchViewById(R.id.title_name);
        tvTitle.setText("个人资料");
        etNickName = serchViewById(R.id.ed_nickName);
        etPhoneNumber = serchViewById(R.id.ed_phoneNumber);
        edBqAccount = serchViewById(R.id.ed_bqAccount);
        btnConfirm = serchViewById(R.id.btn_next);
        btnConfirm.setOnClickListener(this);
        tvUpdatePhoneNo = serchViewById(R.id.tv_updatePhoneNo);
        userHeadImage = serchViewById(R.id.civ_headImage);
        userHeadImage.setOnClickListener(this);

    }

    private void setData() {
        StringBuilder msg = new StringBuilder().append(application.getUserInfo().telNum.substring(0, 3))
                .append("****").append(application.getUserInfo().telNum.substring(7));
        etPhoneNumber.setText(msg);
        Glide.with(PersonalDataActivity.this).load(application.getUserInfo().headimg).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).error(R.mipmap.user_headimg_gray).into(userHeadImage);
        edBqAccount.setText(application.getUserInfo().bqAccount);
        if (!application.equals("")) {
            etNickName.setText(application.getUserInfo().nickname);
        } else {
            etNickName.setText("还没有昵称！");
        }

        etNickName.setSelection(etNickName.length());

    }




    @Override
    public void OnHeadIconPath(String path) {
        if (!TextUtils.isEmpty(path)) {
            userheadImage = path;
            userHeadImage.setImageBitmap(BitmapUtils.getLoacalBitmap(path));
            new Thread(networkTask).start();

        }
    }

    private void upload(){
        if(fileUpload != null){
            fileUpload.setListener(new FileUpload.FileUploadListener() {
                @Override
                public void onUploadStart() {

                }

                @Override
                public void onUploadProgress(long nSize, long allSize) {

                }

                @Override
                public void onUploadFinished(boolean bSuccess, String strResult) {
                        try {
                            JSONObject object = new JSONObject(strResult);
                            String status = object.getString("status");
                            String strHead = object.getString("headimg");
                            if(status.equals("0")){
                                if(!TextUtils.isEmpty(strHead)){
                                    userInfo.headimg = strHead;
                                    toastShow("头像修改成功！");

                                }
                            }else {
                                toastShow("上传失败");
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                }
            });
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.btn_next:
                if (TextUtils.isEmpty(etNickName.getText().toString())) {
                    toastShow("昵称不能为空！");
                    return;
                }
                if (!NetworkUtils.isNetworkAvailable(PersonalDataActivity.this)) {
                    toastShow("当前网络不可用！");
                    return;
                }
                changeNickName();
                break;
            case R.id.civ_headImage:
                CuttingPictureDialog cuttingPictureDialog = new CuttingPictureDialog();
                cuttingPictureDialog.show(getFragmentManager(), "show");
                break;
        }
    }

    Runnable clearCache = new Runnable() {
        @Override
        public void run() {
            Glide.get(PersonalDataActivity.this).clearDiskCache();
        }
    };


    /**
     * 网络操作相关的子线程
     */
    Runnable networkTask = new Runnable() {

        @Override
        public void run() {
            fileUpload.uploadFile(new File(userheadImage),
                    HttpLink.SETTING_HEADIMAGE + "?token=" + userInfo.token);

        }
    };



    private void setImageCacheFile() {
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/biqi");
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }

    }


    private void changeNickName() {
        showSpotsDialog("正在修改");
        Map<String, String> params = new HashMap<>();
        params.put("token", userInfo.token);
        params.put("nickname", Base64.encodeToString(etNickName.getText().toString().getBytes(), Base64.DEFAULT));
        VRHttp.sendRequest(PersonalDataActivity.this, HttpLink.SETING_NICKNAME_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    ResponseBean bean = (ResponseBean) response;
                    if (bean.status.equals("0")) {
                        toastShow("恭喜你！昵称修改成功");
                        finish();
                    }
                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                toastShow("昵称修改失败");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }


}
